package online.inote.naruto.api.access.admin.modules.base.entity;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.experimental.FieldNameConstants;
import org.springframework.util.DigestUtils;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.SortedMap;

/**
 * @description 签名摘要实体对象
 * @author XQF.Sui
 * @date 2021/08/04 15:32
 */
@Data
@FieldNameConstants
@MappedSuperclass
public class SignatureEntity implements Serializable {

  private static final long serialVersionUID = -8622204910745048052L;

  /** 签名摘要 */
  @Column(nullable = false, length = 36)
  protected String signature;

  public String signatureDigest() {
    SortedMap sortedMap = JSON.parseObject(JSON.toJSONString(this), SortedMap.class);
    sortedMap.remove(Fields.signature);

    return DigestUtils.md5DigestAsHex(
        JSON.toJSONString(sortedMap).getBytes(StandardCharsets.UTF_8));
  }

  public void genSignatureDigest() {
    this.signature = signatureDigest();
  }
}
